<template>
  <div class="pet-image-container" :class="{ 'has-error': hasError }">
    <img 
      v-if="!hasError && processedSrc" 
      :src="processedSrc" 
      :alt="alt" 
      class="pet-image"
      @error="handleError"
      @load="handleLoad"
    />
    <img 
      v-else 
      :src="fallbackSrc" 
      :alt="alt" 
      class="pet-image fallback"
    />
    <div v-if="debug && !hasError" class="debug-info">
      <div>源: {{ truncate(src) }}</div>
      <div>处理后: {{ truncate(processedSrc) }}</div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import { getImageUrl, readLocalImage } from '@/utils/image';

export default {
  name: 'PetImage',
  props: {
    src: {
      type: String,
      default: ''
    },
    alt: {
      type: String,
      default: '宠物图片'
    },
    fallbackSrc: {
      type: String,
      default: 'https://via.placeholder.com/200x200?text=Pet+Image'
    },
    debug: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const hasError = ref(false);
    const processedSrc = ref('');
    
    // 处理图片源
    const processImageSource = async () => {
      hasError.value = false;
      
      try {
        if (!props.src) {
          processedSrc.value = '';
          return;
        }
        
        // 如果是本地文件对象
        if (props.src instanceof File) {
          const dataUrl = await readLocalImage(props.src);
          processedSrc.value = dataUrl;
          return;
        }
        
        // 使用工具函数处理URL
        processedSrc.value = getImageUrl(props.src, props.fallbackSrc);
      } catch (error) {
        hasError.value = true;
        processedSrc.value = '';
      }
    };
    
    // 错误处理
    const handleError = () => {
      hasError.value = true;
    };
    
    // 加载成功
    const handleLoad = () => {
      hasError.value = false;
    };
    
    // 截断长文本
    const truncate = (text) => {
      if (!text) return '';
      if (text.length <= 40) return text;
      return text.substring(0, 37) + '...';
    };
    
    // 监听src变化
    watch(() => props.src, () => {
      processImageSource();
    }, { immediate: true });
    
    // 组件挂载时处理图片
    onMounted(() => {
      processImageSource();
    });
    
    return {
      hasError,
      processedSrc,
      handleError,
      handleLoad,
      truncate
    };
  }
}
</script>

<style lang="scss" scoped>
.pet-image-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  
  .pet-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
    
    &.fallback {
      object-fit: contain;
      background-color: #f5f5f5;
    }
  }
  
  &.has-error {
    background-color: #f8d7da;
    border: 1px dashed #dc3545;
  }
  
  .debug-info {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    font-size: 10px;
    padding: 4px;
    word-break: break-all;
  }
}
</style> 